'use strict';

module.exports = app => {
  class RelationsSevice extends app.Service {
    * findAll() {
      const { relation } = this.ctx.model;
      return yield relation.find({}).populate('source target');
    }

    * create(data) {
      const { relation } = this.ctx.model;
      const relationData = yield relation.create(data);
      return yield relation.findOne({ _id: relationData._id }).populate('source target');
    }

    * remove(id) {
      const { relation } = this.ctx.model;
      return yield relation.remove({ _id: id });
    }

    * show(id) {
      const { relation } = this.ctx.model;
      return yield relation.find({ _id: id }).populate('source target');
    }

    * update(params) {
      const { id, data } = params;
      const { relation } = this.ctx.model;
      return yield relation
        .findOneAndUpdate({ _id: id }, data, { new: true })
        .populate('source target');
    }
  }

  return RelationsSevice;
}